import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class SalerManageFrame extends JFrame {
    private JTable salerTable;
    private DefaultTableModel tableModel;

    public SalerManageFrame() {
        setTitle("销售员管理");
        setSize(600, 400);
        setLocationRelativeTo(null);

        // 表格模型
        tableModel = new DefaultTableModel();
        tableModel.addColumn("销售员编号");
        tableModel.addColumn("姓名");
        tableModel.addColumn("性别");
        tableModel.addColumn("业绩");

        salerTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(salerTable);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addBtn = new JButton("添加");
        JButton editBtn = new JButton("修改");
        JButton deleteBtn = new JButton("删除");
        JButton refreshBtn = new JButton("刷新");

        buttonPanel.add(addBtn);
        buttonPanel.add(editBtn);
        buttonPanel.add(deleteBtn);
        buttonPanel.add(refreshBtn);

        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        loadSalerData();

        // 事件监听
        addBtn.addActionListener(e -> {
            new SalerEditDialog(null).setVisible(true);
            loadSalerData();
        });

        editBtn.addActionListener(e -> {
            int selectedRow = salerTable.getSelectedRow();
            if (selectedRow >= 0) {
                String sno = (String) tableModel.getValueAt(selectedRow, 0);
                new SalerEditDialog(sno).setVisible(true);
                loadSalerData();
            } else {
                JOptionPane.showMessageDialog(this, "请选择要修改的行", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        deleteBtn.addActionListener(e -> deleteSaler());
        refreshBtn.addActionListener(e -> loadSalerData());
    }

    private void loadSalerData() {
        tableModel.setRowCount(0);

        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM sale")) {

            while (rs.next()) {
                tableModel.addRow(new Object[]{
                        rs.getString("sno"),
                        rs.getString("sname"),
                        rs.getString("ssex"),
                        rs.getString("sscore")
                });
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void deleteSaler() {
        int selectedRow = salerTable.getSelectedRow();
        if (selectedRow >= 0) {
            String sno = (String) tableModel.getValueAt(selectedRow, 0);

            int confirm = JOptionPane.showConfirmDialog(
                    this,
                    "确定要删除销售员 " + sno + " 吗?",
                    "确认删除",
                    JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                try (Connection conn = DBUtil.getConnection();
                     PreparedStatement pstmt = conn.prepareStatement("DELETE FROM sale WHERE sno = ?")) {

                    pstmt.setString(1, sno);
                    int affectedRows = pstmt.executeUpdate();

                    if (affectedRows > 0) {
                        JOptionPane.showMessageDialog(this, "删除成功");
                        loadSalerData();
                    }
                } catch (SQLException e) {
                    JOptionPane.showMessageDialog(this, "删除失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要删除的行", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }
}

class SalerEditDialog extends JDialog {
    private JTextField snoField, snameField, sscoreField;
    private JComboBox<String> ssexCombo;
    private boolean isEditMode;

    public SalerEditDialog(String sno) {
        if (sno == null) {
            setTitle("添加销售员");
            isEditMode = false;
        } else {
            setTitle("修改销售员");
            isEditMode = true;
        }

        setSize(400, 250);
        setModal(true);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel(new GridLayout(4, 2, 5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        panel.add(new JLabel("销售员编号:"));
        snoField = new JTextField();
        if (isEditMode) snoField.setEditable(false);
        panel.add(snoField);

        panel.add(new JLabel("姓名:"));
        snameField = new JTextField();
        panel.add(snameField);

        panel.add(new JLabel("性别:"));
        String[] sexes = {"男", "女"};
        ssexCombo = new JComboBox<>(sexes);
        panel.add(ssexCombo);

        panel.add(new JLabel("业绩:"));
        sscoreField = new JTextField();
        panel.add(sscoreField);

        JButton saveBtn = new JButton("保存");
        saveBtn.addActionListener(e -> saveSaler());

        JButton cancelBtn = new JButton("取消");
        cancelBtn.addActionListener(e -> dispose());

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        buttonPanel.add(saveBtn);
        buttonPanel.add(cancelBtn);

        add(panel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        if (isEditMode) {
            loadSalerData(sno);
        }
    }

    private void loadSalerData(String sno) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM sale WHERE sno = ?")) {

            pstmt.setString(1, sno);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                snoField.setText(rs.getString("sno"));
                snameField.setText(rs.getString("sname"));
                ssexCombo.setSelectedItem(rs.getString("ssex"));
                sscoreField.setText(rs.getString("sscore"));
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void saveSaler() {
        String sno = snoField.getText().trim();
        String sname = snameField.getText().trim();
        String ssex = (String) ssexCombo.getSelectedItem();
        String sscore = sscoreField.getText().trim();

        // 验证输入
        if (sno.isEmpty() || sname.isEmpty()) {
            JOptionPane.showMessageDialog(this, "销售员编号和姓名不能为空", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try (Connection conn = DBUtil.getConnection()) {
            PreparedStatement pstmt;

            if (isEditMode) {
                pstmt = conn.prepareStatement(
                        "UPDATE sale SET sname=?, ssex=?, sscore=? WHERE sno=?");
                pstmt.setString(1, sname);
                pstmt.setString(2, ssex);
                pstmt.setString(3, sscore);
                pstmt.setString(4, sno);
            } else {
                pstmt = conn.prepareStatement(
                        "INSERT INTO sale (sno, sname, ssex, sscore) VALUES (?, ?, ?, ?)");
                pstmt.setString(1, sno);
                pstmt.setString(2, sname);
                pstmt.setString(3, ssex);
                pstmt.setString(4, sscore);
            }

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                JOptionPane.showMessageDialog(this, "保存成功");
                dispose();
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "保存失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}